package com.yl.order.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.net.yl.ApiRepository;
import com.net.yl.entity.ActivateEntity;
import com.yl.common.ui.BaseActivity;
import com.yl.order.App;
import com.yl.order.R;
import com.yl.order.entity.SyncDeviceWrap;
import com.yl.order.model.ConfigModel;
import com.yl.order.ui.dialog.TipDialogFragment;

/**
 * Created by cjx on 2020-09-08
 * 说明：
 */
public class SnSettingActivity extends BaseActivity {

    private EditText numberView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sn_setting);

        findViewById(R.id.close).setOnClickListener(v -> finish());

        numberView = findViewById(R.id.number);
        numberView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 12) {
                    activate();
                }
            }
        });
    }

    private void activate() {
        String number = numberView.getText().toString().toUpperCase();
        if (number.equals("000000000000")) {
            ActivateEntity device = new ActivateEntity();
            device.setSn(number);
            App.app.activateInfo = device;

            ConfigModel.saveActivate(device);
            setResult(RESULT_OK);
            finish();
            return;
        }
        showLoading("正在激活");
        ApiRepository.getInstance().activate(number, response -> {
            hideLoading();
            if (response.isSuccess()) {
                ActivateEntity data = response.data;
                data.setSn(number);
                App.app.activateInfo = data;
                ConfigModel.saveDeviceWrap(new SyncDeviceWrap(data, null, null));
                setResult(RESULT_OK);
                finish();
            } else {
                numberView.setText(null);
                showTip(response.message);
            }
        }, throwable -> {
            hideLoading();
            numberView.setText(null);
            showTip(throwable.getMessage());
        });
    }

    private void showTip(String message) {
        TipDialogFragment.newInstance()
                .setDescribe(message)
                .show(getSupportFragmentManager(), "tip");
    }
}
